import { defineStore } from 'pinia'
import { store } from '../index'
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import en from 'element-plus/es/locale/lang/en'
import zh_tw from 'element-plus/es/locale/lang/zh-tw'
import jp from 'element-plus/es/locale/lang/ja'
import { CACHE_KEY, useCache } from '@/hooks/web/useCache'
import { LocaleDropdownType } from '@/types/localeDropdown'

// element plus 多语言
const elLocaleMap = {
  zh: zhCn,
  en: en,
  // element plus 只有zh-tw语言包，不要动
  'zh-tw': zh_tw,
  ja: jp
}
// 后台的key和前端的不一致
const axiosI18nMap = {
  zh: 'zh_CN',
  en: 'en_US',
  // element plus 只有zh-tw语言包，不要动
  'zh-HK': 'zh_HK',
  ja: 'ja_JP'
}
interface LocaleState {
  currentLocale: LocaleDropdownType
  localeMap: LocaleDropdownType[]
  axiosLangHeader: String
}

export const useLocaleStore = defineStore('locales', {
  state: (): LocaleState => {
    // 必须用localStorage 兼容低代码
    const langeKey = localStorage.getItem(CACHE_KEY.LANG) || 'zh'
    return {
      currentLocale: {
        lang: langeKey,
        elLocale: elLocaleMap[langeKey]
      },
      axiosLangHeader: axiosI18nMap[langeKey],
      // 多语言
      localeMap: [
        {
          lang: 'zh',
          name: '简体中文'
        },
        // {
        //   lang: 'zh-HK',
        //   name: '繁體中文'
        // },
        {
          lang: 'en',
          name: 'English'
        },
        {
          lang: 'ja',
          name: 'にほん'
        }
      ]
    }
  },
  getters: {
    getCurrentLocale(): LocaleDropdownType {
      return this.currentLocale
    },
    getLocaleMap(): LocaleDropdownType[] {
      return this.localeMap
    },
    getAxiosLangHeader(): String {
      return this.axiosLangHeader
    }
  },
  actions: {
    setCurrentLocale(localeMap: LocaleDropdownType) {
      this.currentLocale.lang = localeMap?.lang
      this.currentLocale.elLocale = elLocaleMap[localeMap?.lang]
      this.axiosLangHeader = axiosI18nMap[localeMap?.lang]
      // 必须用localStorage 兼容低代码
      localStorage.setItem(CACHE_KEY.LANG, localeMap?.lang)
      // 把路由缓存删除，从接口重新获取
      const { wsCache } = useCache()
      wsCache.delete(CACHE_KEY.USER)
      wsCache.delete(CACHE_KEY.ROLE_ROUTERS)
      // 删除字典数据
      const { wsCache: sessionCache } = useCache('sessionStorage')
      sessionCache.delete(CACHE_KEY.DICT_CACHE)
    }
  }
})

export const useLocaleStoreWithOut = () => {
  return useLocaleStore(store)
}
